// 属性： 宽度，高度，横坐标，纵坐标，横向速度，纵向速度，对应的dom对象
const bardDmo = document.querySelector(".bird"); // 获取天空元素
const bardStyles = getComputedStyle(bardDmo); // 获取元素的样式
const bardWidth = parseFloat(bardStyles.width);
const bardHeight = parseFloat(bardStyles.height);
const bardTop = parseFloat(bardStyles.top);
const bardLeft = parseFloat(bardStyles.left);

// 小鸟类
class Bard extends Rectangle {
  constructor() {
    super(bardWidth, bardHeight, bardLeft, bardTop, 0, 0, bardDmo);
    this.g = 1500; // 小鸟向下的加速度， 单位：像素/秒
    this.swingStatus = 1; // 小鸟翅膀状态
    this.maxY = landTop - bardHeight; // 小鸟top最大值
    /**受保护的次数 */
    this.protect = 0;
    /**無敵 */
    this.miss = false;
    /**小鳥狀態 */
    this.status = "normal";
    this.game = null;
  }

  move(duration) {
    super.move(duration);
    // 根据加速度改变下落速度
    if (this.g == 0) {
      this.ySpeed = 0;
    } else {
      this.ySpeed += this.g * duration;
    }
  }

  /**生成安全套 */
  renderProtect(bool) {
    this.protect = bool ? 1 : 0;
    if (this.protect > 0) {
      bardDmo.style.border = "1px solid red";
    } else {
      bardDmo.style.border = "none";
      this.protectTime(1.5);
    }
  }

  /**小鳥衝刺 */
  sprint({ time = 5, game }) {
    this.game = game;
    this.status = "sprint";
    this.protectTime(time + 0.5);
  }

  /**管道透明 */
  pipeOpacity({ game, time }) {
    this.game = game;
    this.status = "opacity";
    this.protectTime(time);
  }

  /**
   * 无敵時間 單位秒
   * @param {number} time
   */
  protectTime(time) {
    this.miss = true;

    if (this.status == "sprint") {
      this.g = 0;
      this.game.upSpeed(10);
      bardDmo.style.backgroundColor = "yellow";
    } else if (this.status == "opacity") {
      this.game.pipeProducer.opacityFun(); // 使管道变透明
    }

    setTimeout(() => {
      this.miss = false;

      if (this.status == "sprint") {
        bardDmo.style.backgroundColor = "transparent";
        this.g = 1500;
        this.game.pipeProducer.removeAll();
        /** 冲刺结束后恢复原来的速度 */
        this.game.checkSpeedIncrease( getCookie("difficulty") || 1);
      } else if (this.status == "opacity") {
        this.game.pipeProducer.opacityFun(1);
      }

      this.status = "normal";
    }, 1000 * time);
  }

  onMove() {
    // 控制鸟的范围
    if (this.top <= 0) {
      this.top = 0;
    } else if (this.top >= this.maxY) {
      this.top = this.maxY;
    }
    this.swing(); // 渲染之前修改翅膀状态
  }

  // 向上跳， 直接给一个向上的速度
  jump() {
    this.ySpeed = -400;
  }

  // 小鸟扇动翅膀
  swing() {
    if (this.ySpeed > 100) {
      this.swingStatus = 1;
    } else if (this.ySpeed < 0) {
      this.swingStatus = 3;
    } else {
      this.swingStatus = 2;
    }
  }

  render() {
    super.render();
    bardDmo.className = `bird swing${this.swingStatus}`; // 改变翅膀状态
  }
}
